<?php
declare (strict_types = 1);

namespace app\admin\controller;

use think\Db;
use think\Session;
use think\captcha\Captcha;
use app\admin\model\AdminUser;

/**
 * 登录控制器
 * Class Login
 * @package app\admin\controller
 */
class Login extends BaseController
{
    /**
     * 检查登录状态 - 重写父类方法
     */
    protected function checkLogin()
    {
        // 登录控制器不需要检查登录状态
        return true;
    }
    
    /**
     * 显示登录页面
     */
    public function index()
    {
        // 如果已经登录，直接跳转到后台首页
        if (Session::has('admin_id')) {
            $this->redirect('/admin/dashboard');
        }
        
        return view();
    }
    
    /**
     * 生成验证码
     */
    public function captcha()
    {
        $captcha = new Captcha([
            'length' => 4,
            'fontSize' => 16,
            'useCurve' => true,
            'useNoise' => true,
            'imageW' => 120,
            'imageH' => 45,
            'bg' => [255, 255, 255]
        ]);
        return $captcha->entry();
    }
    
    /**
     * 处理登录请求
     */
    public function authenticate()
    {
        $username = $this->request->param('username', '');
        $password = $this->request->param('password', '');
        $captcha = $this->request->param('captcha', '');
        $remember = $this->request->param('remember', 0);
        
        // 基础验证
        if (empty($username) || empty($password)) {
            return json(['code' => 400, 'msg' => '用户名和密码不能为空']);
        }
        
        // 暂时禁用验证码验证
        // if (empty($captcha)) {
        //     return json(['code' => 1, 'msg' => '请输入验证码']);
        // }
        // 
        // // 验证码验证
        // if (!captcha_check($captcha)) {
        //     return json(['code' => 1, 'msg' => '验证码错误']);
        // }
        
        try {
            // 使用AdminUser模型验证登录
            $result = AdminUser::login($username, $password);
            
            if ($result['code'] === 0) {
                $user = $result['data'];
                
                // 设置Session
                Session::set('admin_id', $user->id);
                Session::set('admin_username', $user->username);
                Session::set('admin_info', [
                    'id' => $user->id,
                    'username' => $user->username,
                    'real_name' => $user->real_name,
                    'email' => $user->email,
                    'phone' => $user->phone,
                    'last_login_time' => $user->last_login_time
                ]);
                
                // 记住登录状态
                if ($remember) {
                    cookie('admin_remember', $user->id, 7 * 24 * 3600); // 7天
                }
                
                // 记录登录日志
                $this->logLogin($user->username, true, '登录成功', $this->request->ip());
                
                return json(['code' => 200, 'msg' => '登录成功']);
            } else {
                // 记录登录失败日志
                $this->logLogin($username, false, $result['msg'], $this->request->ip());
                return json(['code' => 400, 'msg' => $result['msg']]);
            }
            
        } catch (\Exception $e) {
            // 记录异常日志
            $this->logLogin($username, false, '系统异常：' . $e->getMessage(), $this->request->ip());
            return json(['code' => 500, 'msg' => '登录失败，请稍后重试']);
        }
    }
    
    /**
     * 退出登录
     */
    public function logout()
    {
        try {
            $adminInfo = Session::get('admin_info');
            
            // 记录退出日志
            if ($adminInfo) {
                $this->logLogin($adminInfo['username'], true, '退出登录', $this->request->ip());
            }
            
            // 清除Session和Cookie
            Session::clear();
            cookie('admin_remember', null);
            
            // 如果是AJAX请求，返回JSON
            if ($this->request->isAjax()) {
                return json(['code' => 0, 'msg' => '退出成功', 'redirect' => '/admin/login']);
            }
            
            // 否则重定向
            return redirect('/admin/login');
        } catch (\Exception $e) {
            if ($this->request->isAjax()) {
                return json(['code' => 1, 'msg' => '退出失败：' . $e->getMessage()]);
            }
            return redirect('/admin/login');
        }
    }
    
    /**
     * 记录登录日志
     * @param string $username 用户名
     * @param bool $success 是否成功
     * @param string $message 消息
     * @param string $ip IP地址
     */
    private function logLogin($username, $success, $message = '', $ip = '')
    {
        try {
            $logData = [
                'username' => $username,
                'action' => $success ? '登录成功' : '登录失败',
                'message' => $message,
                'ip' => $ip ?: $this->request->ip(),
                'user_agent' => $this->request->header('User-Agent'),
                'created_at' => date('Y-m-d H:i:s')
            ];
            
            // 直接写入数据库（如果表不存在不影响登录）
            try {
                Db::name('login_logs')->insert($logData);
            } catch (\Exception $e) {
                // 日志表不存在，静默忽略
            }
        } catch (\Exception $e) {
            // 日志记录失败不影响登录流程
            trace('登录日志记录失败：' . $e->getMessage(), 'error');
        }
    }
}
